package DBLayer;

import Model.Employee;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

/**
 *
 * @author Administrator
 */
public class DbEmployee implements DbInterfaceEmployee {
	private Connection db_con;

	public DbEmployee() {
		db_con = DbConnection.getInstance().getDBcon();
	}

	public ArrayList<Employee> getAllEmployees(String wClause) {
		return miscWhere(wClause);
	}

        public Employee searchByName(String name){
            String wClause = "name = '"+ name +"'";
            return singleWhere(wClause);
        }

	public Employee searchById(String id) {
		String wClause = "id = '"+id+"'";
		return singleWhere(wClause);
	}

	public Employee searchByPhone(String phone) {
		String wClause = "phone = '"+phone+"'";
		return singleWhere(wClause);
	}

	public Employee searchByEmail(String email) {
		String wClause = "email = '"+email+"'";
		return singleWhere(wClause);
	}

	public int insertEmployee(Employee emp) {
		int result = -1;
		String query = "INSERT INTO employees(name, address, zip, city, phone, email) VALUES"
				+ "('" + emp.getName() + "', '" + emp.getAddress() + "', '" + emp.getZip()
				+ "', '" + emp.getCity() + "', '" + emp.getPhone() + "', '" + emp.getEmail() + "')";
		System.out.println("insert: " + query);
		try {
			Statement stmt = db_con.createStatement();
			stmt.setQueryTimeout(5);
			result = stmt.executeUpdate(query);
			stmt.close();
		} catch (Exception ex) {
			System.out.println("Insert exception in employee db: " + ex);
		}
		return result;
	}

	public int updateEmployee(Employee emp)
	{
		int result = -1;

		String query="UPDATE employees SET ";
		if (emp.getName() != null) query += "name = '"+emp.getName()+"',";
		if (emp.getAddress() != null) query += "address = '"+emp.getAddress()+"',";
		if (emp.getZip() != null) query += "zip = '"+emp.getZip()+"',";
		if (emp.getCity() != null) query += "city = '"+emp.getCity()+"',";
		if (emp.getPhone() != null) query += "phone = '"+emp.getPhone()+"',";
		if (emp.getEmail() != null) query += "email = '"+emp.getEmail()+"',";
		if (query.endsWith(",")) query = query.substring(0, query.length()-1);
		query += " WHERE id = "+ emp.getId();
                System.out.println("Update query:" + query);
  		try{ // update employee
	 		Statement stmt = db_con.createStatement();
	 		stmt.setQueryTimeout(5);
	 	 	result = stmt.executeUpdate(query);

	 	 	stmt.close();
		}//slut try
	 	catch(Exception ex){
	 	 	System.out.println("Update exception in employee db: "+ex);
	  	}
		return result;
	}

	public int deleteEmployee(String phone) {
		int result = -1;

	  	String query = "DELETE FROM employees WHERE phone = '" +
				phone + "'";
                System.out.println("delete: " + query);
	  	try{ // delete from employees
	 		Statement stmt = db_con.createStatement();
	 		stmt.setQueryTimeout(5);
	 	  	result = stmt.executeUpdate(query);
	 	  	stmt.close();
  		}//slut try
   	        catch(Exception ex){
	 	  	System.out.println("Delete exception in employee db: "+ex);
   	        }
		return result;
	}

	private ArrayList<Employee> miscWhere(String wClause)
	{
        ResultSet results;
	    ArrayList<Employee> list = new ArrayList<Employee>();

	    String query =  buildQuery(wClause);

        try{ // read the employee from the database
			Statement stmt = db_con.createStatement();
			stmt.setQueryTimeout(5);
			results = stmt.executeQuery(query);

			int snr=0;
			while( results.next() ){
				Employee empObj = new Employee();
				empObj = buildEmployee(results);
		        list.add(empObj);
			}//end while
			stmt.close();
		} catch(Exception e){
	 		System.out.println("Query exception - select: "+e);
			e.printStackTrace();
	 	}
		return (list.size() > 0 ? list : null);
	}

	//Singelwhere is used when we only select one employee
	private Employee singleWhere(String wClause)
	{
		ResultSet results;
		Employee empObj = null;
	    String query =  buildQuery(wClause);
        System.out.println(query);
		try{ // read the employee from the database
	 		Statement stmt = db_con.createStatement();
	 		stmt.setQueryTimeout(5);
	 		results = stmt.executeQuery(query);

	 		if( results.next() ){
				empObj = buildEmployee(results);
				stmt.close();
			}
		} catch(Exception e) {
	 		System.out.println("Query exception: " + e);
	 	}
		return empObj;
	}
	
	//method to build the query
	private String buildQuery(String wClause)
	{
	    String query="SELECT * FROM employees";

		if (wClause.length()>0)
			query=query+" WHERE "+ wClause;

		return query;
	}

		//method to build an employee object
	private Employee buildEmployee(ResultSet results)
	{
		Employee empObj = new Employee();
        try {
			empObj.setId(Integer.parseInt(results.getString(1)));
                        empObj.setName(results.getString(2));
                        empObj.setAddress(results.getString(3));
                        empObj.setZip(results.getString(4));
			empObj.setCity(results.getString(5));
			empObj.setPhone(results.getString(6));
			empObj.setEmail(results.getString(7));
		} catch(Exception e) {
			System.out.println("error in building the employee object");
        }
		return empObj;
	}
}
